# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggplot2)
library(ggrepel)
library(plyr)
library(dplyr)
library(tidyr)
library(tibble)
library(gridExtra)
library(purrr)
library(scales)
library(egg)
library(optparse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

sampleColDf <- read.table(opt$sc, header = T, sep = "\t", stringsAsFactors = F, comment.char = "") %>%
select(c("ClassNote", "col"))
sampleCols <- sampleColDf %>%
deframe()

classNotes <- sampleInfo %>%
.$ClassNote %>%
unique()
cn <- combn(classNotes, 2)
for (i in 1 : ncol(cn)) {
    row <- cn[, i]
    group1Name <- row[1]
    group2Name <- row[2]
    parent <- paste0(group2Name, "_", group1Name)
    createWhenNoExist(parent)
    fileName <- paste0(parent, "/Diff_Table_", group2Name, "_", group1Name, ".csv")
    outFileName <- paste0(parent, "/Vioplot_Top9_", group2Name, "_", group1Name, ".pdf")
    pValueData <- read.csv(fileName, header = T, stringsAsFactors = F, comment.char = "") %>%
        arrange(Pvalue) %>%
        head(9)
    names <- pValueData$Name

    data <- read.csv(opt$i, header = T, stringsAsFactors = FALSE) %>%
        select(- c("HMDB", "KEGG")) %>%
        filter(! startsWith(Name, "Unknown")) %>%
        select(- Class) %>%
        gather("SampleID", "Value", - Name) %>%
        inner_join(sampleInfo, by = c("SampleID")) %>%
        filter(ClassNote %in% c(group1Name, group2Name))

    head(data)

    getP <- function(name){
        pData <- data %>% filter(Name == name)
        pValueDf <- pValueData %>% filter(Name == name)
        p <- ggplot(pData, mapping = aes(x = ClassNote, y = Value, fill = ClassNote)) +
            theme_bw(base_size = 8, base_family = "Times") +
            theme(axis.text.x = element_text(size = 8, vjust = 0.5),
            axis.text.y = element_text(size = 8), legend.position = 'none',
            axis.title.y = element_text(size = 11), legend.margin = margin(t = 0.3, b = 0.1, unit = 'cm'),
            legend.text = element_text(size = 6), axis.title.x = element_text(size = 11), panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(), plot.title = element_text(hjust = 0.5, size = 8)
            ) +
            xlab("") +
            ylab("") +
            ggtitle(paste0(pValueDf$Name, "\n", "P=", scientific(pValueDf$Pvalue, 2))) +
            scale_fill_manual("", values = sampleCols) +
            geom_violin() +
            geom_boxplot(width = 0.1, fill = "white")
        return(p)
    }

    p <- names %>%
    map(getP)

    iEnd <- min(length(p), 3)
    p[1 : iEnd] = p[1 : iEnd] %>%
    map(~ .x + theme(plot.margin = margin(t = 0.5, unit = "cm")))

    pdf(outFileName, 7.5, 9)
    layout <- matrix(1 : length(names), byrow = T, ncol = 3)
    ggarrange(plots = p, newpage = FALSE, top = NULL, layout_matrix = layout)
    dev.off()
}



